import { defineEventHandler, getQuery, readBody } from 'h3'
import { query } from '../utils/db' // 确保路径正确
import dayjs from 'dayjs'
import { ResponseCode, sendSuccessResponse, sendErrorResponse } from '~/server/utils/response'


interface Page {
  page_id: string | number
  title: string
  content: string
  create_time: string
  update_time: string
}

export default defineEventHandler(async (event) => {
  const method = event.node.req.method

  // 分页查询
  if (method === 'GET') {
    try {
      const queryParams = getQuery(event)
      const page = Number(queryParams.page) || 1
      const size = Number(queryParams.size) || 10
      const cursorId = queryParams.cursorId as string | undefined

      // 获取总数
      const countResult = await query('SELECT COUNT(*) as total FROM page')
      const total = countResult.results[0]?.total ?? 0

      let sql: string
      let params: (string | number)[]

      if (cursorId) {
        sql = 'SELECT * FROM page WHERE page_id < ? ORDER BY page_id DESC LIMIT ?'
        params = [cursorId, size]
      } else {
        sql = 'SELECT * FROM page ORDER BY page_id DESC LIMIT ?, ?'
        params = [(page - 1) * size, size]
      }

      const { results } = await query(sql, params)
      const data = results as Page[]
      return sendSuccessResponse(event, {
        list: data,
        pagination: {
          total,
          currentPage: page,
          perPage: size,
          lastCursor: data.length > 0 ? data[data.length - 1].page_id : null
        }
      }, '获取列表成功')
    } catch (error: any) {
      return sendErrorResponse(event, ResponseCode.BAD_REQUEST, error?.message || '获取列表失败')
    }
  }

  // 创建
  if (method === 'POST') {
    try {
      const body = await readBody(event)
      const time = dayjs().format('YYYY-MM-DD HH:mm:ss')
      const { results } = await query(
        'INSERT INTO page SET ?',
        [{ ...body, create_time: time, update_time: time }]
      )
      return sendSuccessResponse(event, { id: results.insertId }, '创建成功')
    } catch (error: any) {
      return sendErrorResponse(event, ResponseCode.BAD_REQUEST, error?.message || '创建失败')
    }
  }

  // 更新
  if (method === 'PUT') {
    console.log('开始处理PUT请求')

    try {
      const body = await readBody(event)
      console.log('请求体数据:', body)

      const { id, name, content } = body

      if (!id) {
        console.error('缺少必要参数: id')
        // throw createError({
        //   statusCode: 400,
        //   statusMessage: 'ID is required'
        // })
        return sendErrorResponse(event, ResponseCode.BAD_REQUEST, 'ID is required')
      }

      const updateData = {
        name,
        content,
        update_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
      }

      console.log('准备更新的数据:', updateData)

      const filteredUpdateData = Object.fromEntries(
        Object.entries(updateData).filter(([_, value]) => value !== undefined && value !== null)
      )

      console.log('过滤后的更新数据:', filteredUpdateData)

      const { results } = await query(
        'UPDATE page SET ? WHERE page_id = ? LIMIT 1',
        [filteredUpdateData, id]
      )

      console.log('完整数据库响应:', results)

      if (!results) {
        console.error('数据库查询返回空结果')
        // throw createError({
        //   statusCode: 500,
        //   statusMessage: '数据库查询失败'
        // })
        return sendErrorResponse(event, ResponseCode.INTERNAL_ERROR, '数据库查询失败')

      }

      console.log('受影响行数:', results.affectedRows)

      // return {
      //   success: results.affectedRows > 0,
      //   affectedRows: results.affectedRows,
      //   message: results.affectedRows > 0 ? '更新成功' : '没有记录被更新',
      //   updatedId: id
      // }
      return sendSuccessResponse(event, {
        updatedId: id,
      }, results.affectedRows > 0 ? '更新成功' : '没有记录被更新',)

    } catch (error: any) {
      console.error('处理PUT请求时出错:', error)
      // throw createError({
      //   statusCode: 500,
      //   statusMessage: error?.message || '更新记录时出错',
      //   data: {
      //     originalError: error
      //   }
      // })
      return sendErrorResponse(event, ResponseCode.INTERNAL_ERROR, error?.message || '更新记录时出错')

    }
  }

  // 删除
  if (method === 'DELETE') {
    try {
      const { id } = getQuery(event)
      const { results } = await query(
        'DELETE FROM page WHERE page_id = ? LIMIT 1',
        [id as string]
      )
      // return { affectedRows: results.affectedRows }
      return sendSuccessResponse(event, {
        updatedId: id,
      }, '删除成功')
    } catch (error: any) {
      return sendErrorResponse(event, ResponseCode.BAD_REQUEST, error?.message || '删除失败')
    }
  }
})